<template>
  <div
    class="report-list-container"
    ref="reportListPage"
    v-loading.fullscreen.lock="loadingListData"
  >
    <div class="report-list-title-group-container">
      <div class="title">人员工单数据统计</div>
      <div>可统计每个人员的工单满意度、营收等信息。</div>
    </div>
    <!--搜索-->
    <div class="report-list-search-group-container">
      <form class="base-search" onsubmit="return false;">
        <div class="report-list-base-search-group">
          <biz-team-select multiple collapse :value="tag" @input="chooseTeam" @remove="clearTeam"/>
          <el-select v-model="params.userIds" filterable multiple collapse-tags @change="chooseSearch" clearable placeholder="请选择人员" >
            <el-option
              v-for="item in tagUsers"
              :key="item.userId"
              :label="item.displayName"
              :value="item.userId">
            </el-option>
          </el-select>
          <el-date-picker
            v-model="params.dateRange"
            @change="chooseSearch"
            type="datetimerange"
            :picker-options="pickerOptions"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="timestamp"
            :default-time="['00:00:00', '23:59:59']"
            align="right">
          </el-date-picker>
          <base-button type="primary" @event="resetParams">重置</base-button>
        </div>
      </form>
    </div>

    <!--list start-->
    <div class="report-list-component">
      <!--operation bar start-->
      <div class="operation-bar-container">
        <div class="top-btn-group">
          <base-button type="primary" @event="exportReport(false)" v-if="isButtonDisplayed">导出</base-button>
          <base-button type="primary" @event="exportReport(true)" v-if="isButtonDisplayed">导出全部</base-button>
        </div>
      </div>
      <!--operation bar end-->

      <el-table
        v-table-style
        :data="reports"
        stripe
        :highlight-current-row="false"
        header-row-class-name="report-table-header"
        ref="multipleTable"
        class="report-table"
      >
        <el-table-column type="index" width="48" align="center" label="序号" fixed :index="indexMethod"></el-table-column>
        <el-table-column
          v-for="(column, index) in columns"
          v-if="column.show"
          :key="`${column.field}_${index}`"
          :label="column.label"
          :prop="column.field"
          :width="column.width"
          :min-width="column.minWidth || '120px'"
          :align="column.align"
          :fixed="column.fixed"
        >
          <template slot-scope="scope">
            <span>{{scope.row[column.field]}}</span>
          </template>
        </el-table-column>
      </el-table>

      <div class="table-footer">
        <div class="list-info">
          共
          <span class="level-padding">{{totalItems}}</span>记录
        </div>
        <el-pagination
          class="report-table-pagination"
          background
          @current-change="jump"
          @size-change="handleSizeChange"
          :page-sizes="defaultTableData.defaultPageSizes"
          :page-size="params.pageSize"
          :current-page="params.pageNum"
          layout="prev, pager, next, sizes, jumper"
          :total="totalItems"
        ></el-pagination>
      </div>
    </div>
    <!--list end-->

    <!-- start 导出工单 -->
    <base-export
      ref="exportPanel"
      :columns="exportColumns"
      :build-params="buildExportParams"
      :validate="checkExportCount"
      method="post"
      :action="taskReportExport"
    />
    <!-- end 导出客户 -->


  </div>
</template>

<script>
import { formatDate, nearDateBy, dayTimeEnd } from 'pub-bbx-utils';
import {personReport, getUserByTags} from '@src/api/userReportCustom.ts';
import { checkButtonDisplayed } from '@src/util/dom';
import { safeNewDate } from '@src/util/time';
/* export & import */
import { taskReportExport } from '@src/api/Export';
import { defaultTableData } from '@src/util/table'
// import { eventListImport_1, eventListImportTem_1 } from '@src/api/Import';
export default {
  name: 'report-list-view',
  props: {
    initData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      defaultTableData,
      // self state
      isButtonDisplayed: checkButtonDisplayed(),
      pickerMinDate:'', // 第一次选中的时间
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            picker.$emit('pick', [moment().subtract(6, 'days'), moment()]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            picker.$emit('pick', [moment().subtract(1, 'month'), moment()]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            picker.$emit('pick', [moment().subtract(3, 'month'), moment()]);
          }
        }],
        onPick:(val)=>{
          this.pickerMinDate = safeNewDate(val.minDate).getTime();
        },
        // 设置跨度1年
        disabledDate:(time)=>{
          if(this.pickerMinDate){
            let maxTime = moment(this.pickerMinDate).add(1, 'year');
            let minTime = moment(this.pickerMinDate).subtract(1, 'year');
            return time.getTime() > maxTime || time.getTime() < minTime;
          }
        }
      },
      loadingListData: false,
      params: {
        tagIds:[],
        userIds:[],
        dateRange: [+nearDateBy(6, 'day'), +dayTimeEnd()],
        pageNum: 1,
        pageSize: 10
      },
      tagUsers:[],
      tag:[],
      totalItems: 0,
      // data from remote
      reports: [],
      exportType:true,
      columns: this.fixedColumns(),
      taskReportExport
    };
  },
  computed: {
    editedPermission() {
      return this.auth.report_EDIT;
    },
    createdPermission() {
      return this.auth.report_CREATE;
    },
    viewedPermission() {
      return this.auth.report_VIEW === 3;
    },
    deletePermission() {
      return this.auth.report_EDIT === 3 && this.auth.report_DELETE;
    },
    exportPermission() {
      return this.auth.EXPORT_IN;
    },
    auth() {
      return this.initData.auth || {};
    },
    smsRest() {
      return this.initData.smsRest || 0;
    },
    exportColumns() {
      return this.columns.map(c => {
        c.export = true;

        return c;
      });
    },
  },
  async mounted() {
    this.revertStorage()
    this.getUserByTags()
    this.search();
  },
  methods: {
    async clearTeam(value = []){
      this.params.tagIds = [];
      this.tag = []
      await this.getUserByTags()
      await this.search();
    },
    chooseSearch(){
      this.search();
    },
    async chooseTeam(value){
      this.tag = value
      const ids = []
      value.forEach(item=>{
        ids.push(item.id || item)  
      })
      this.params.tagIds = ids;
      this.params.userIds = []
      await this.getUserByTags()
      await this.search();
    },
    getUserByTags(){
      getUserByTags({tagIds:this.params.tagIds}).then(res=>{
        if(res.status === 0){
          this.tagUsers = res.data
        }
      })
    },
    /** 构建客户导出参数 */
    buildExportParams(checkedArr, ids) {
      let exportAll = !ids || ids.length == 0;
      let exportSearchModel = exportAll
        ? {
          ...this.buildParams(),
          exportTotal: this.totalItems
        }
        : { exportTotal: ids.length };
        // 判断是否导出全部
      exportSearchModel.pageSize = this.exportType ? 0 : exportSearchModel.pageSize 
      return {
        reportChecked: checkedArr.join(','),
        exportSearchModel: JSON.stringify(exportSearchModel)
      };
    },
    /** 导出客户 */
    exportReport(exportAll) {
      let ids = [];
      let fileName = '人员工单数据统计数据.xlsx';
      this.exportType = exportAll
      this.$refs.exportPanel.open(ids, fileName);
    },
    /** 检测导出条数 */
    checkExportCount(ids, max) {
      let exportAll = !ids || ids.length == 0;
      return exportAll && this.totalItems > max
        ? '为了保障响应速度，暂不支持超过5000条以上的数据导出，请您分段导出。'
        : null;
    },


    search() {
      const params = this.buildParams();

      this.loadingListData = true;
      
      return personReport(params).then(res=>{
        if (!res || !res.list) {
          this.reports = [];
          this.totalItems = 0;
          this.params.pageNum = 1;
        } else {
          const { total, pageNum, list} = res;

          this.reports = list
          this.totalItems = total;
          this.params.pageNum = pageNum;
        }

        return res;
      })
        .then(() => {
          this.$refs.reportListPage.scrollTop = 0;
          this.loadingListData = false;
        })
        .catch(err => {
          this.loadingListData = false;
          console.error('err', err);
        });
    },
    buildParams() {
      const sm = Object.assign({}, this.params);
      let params = {
        timeStart: sm.dateRange[0],
        timeEnd: sm.dateRange[1],
        tagIds: sm.tagIds,
        userIds:sm.userIds,
        pageSize: sm.pageSize,
        pageNum: sm.pageNum
      };

      return params;
    },

  
    jump(pageNum) {
      this.params.pageNum = pageNum;
      this.search();
    },
    // common methods
    getLocalStorageData() {
      const dataStr = localStorage.getItem('taskReportData') || '{}';
      return JSON.parse(dataStr);
    },
    saveDataToStorage(key, value) {
      const data = this.getLocalStorageData();
      data[key] = value;
      localStorage.setItem('taskReportData', JSON.stringify(data));
    },
    revertStorage() {
      const { pageSize } = this.getLocalStorageData();
      if (pageSize) {
        this.params.pageSize = pageSize;
      }
    },
    handleSizeChange(pageSize) {
      this.saveDataToStorage('pageSize', pageSize);
      this.params.pageNum = 1;
      this.params.pageSize = pageSize;
      this.search();
    },
    resetParams() {
      window.TDAPP.onEvent('pc：人员工单统计数据-重置事件');
      this.tag = []
      this.params = {
        tagIds: [],
        userIds:[],
        pageNum: 1,
        pageSize: this.params.pageSize,
        dateRange:[+nearDateBy(6, 'day'), +dayTimeEnd()],

      };

      this.search();
    },
    indexMethod(index){
      return this.params.pageSize * (this.params.pageNum - 1) + index + 1
    },
    // getSummaries(param){
    //   const { columns, data } = param;
    //   let sums = [];
    //   columns.forEach((column, index) => {
    //     if (index === 0) {
    //       sums[index] = '合计';
    //       return;
    //     }else if(index === 1 || index === 2){
    //       sums[index] = '';
    //       return;
    //     }
        
    //     const values = data.map(item => Number(item[column.property]));
    //     if (!values.every(value => isNaN(value))) {
    //       sums[index] = values.reduce((prev, curr) => {
    //         const value = Number(curr);
    //         if (!isNaN(value)) {
    //           return prev + curr;
    //         } 
    //         return prev;
              
    //       }, 0);
    //       sums[index] += '';
    //     } else {
    //       sums[index] = '';
    //     }
    //   });
    //   sums = sums.map(item=>{
    //     if(item && item != '合计' && item != '0'){
    //       item = Number(item).toFixed(2)
    //     }
    //     return item
    //   })
    //   return sums;
    // },

    fixedColumns() {
      return [
        {
          label: '区域',
          field: 'tagName',
          show: true,
          fixed: true,
        },
        {
          label: '维修工程师',
          field: 'userName',
          fixed: true,
          show: true,
        },
        {
          label: '订单总数',
          field: 'totalTaskCount',
          show: true
        },
        {
          label: '保内单数',
          field: 'warrantyTaskCount',
          show: true
        },
        {
          label: '保外单数',
          field: 'insuredTaskCount',
          show: true
        },
        {
          label: '订单超时',
          field: 'overTimeTaskCount',
          show: true
        },
        {
          label: '工单超时率(%)',
          field: 'overTimeTaskRatio',
          show: true
        },
        {
          label: '满意度平均分',
          field: 'satisfiedAverage',
          show: true,
        },
        {
          label: '满意率(%)',
          field: 'satisfiedRatio',
          show: true,
        },
        {
          label: '回访总单数',
          field: 'reviewTaskCount',
          show: true,
        },
        {
          label: '满意次数',
          field: 'satisfiedCount',
          show: true
        },
        {
          label: '占比(%)',
          field: 'satisfiedProportion',
          show: true
        },
        {
          label: '服务态度不满意次数',
          field: 'serviceDissatisfiedCount',
          show: true,
          minWidth:'150px'
        },
        {
          label: '占比(%)',
          field: 'serviceDissatisfiedProportion',
          show: true,
          minWidth:'80px'
        },
        {
          label: '维修结果不满意次数',
          field: 'maintenanceResultsDissatisfiedCount',
          show: true,
          minWidth:'150px'
        },
        {
          label: '占比(%)',
          field: 'resultDissatisfiedProportion',
          show: true,
          minWidth:'80px'
        },
        {
          label: '维修及时不满意次数',
          field: 'maintenanceTimelyDissatisfiedCount',
          show: true,
          minWidth:'150px'
        },
        {
          label: '占比(%)',
          field: 'timelyDissatisfiedProportion',
          show: true,
          minWidth:'80px'
        },
        {
          label: '工单应收款',
          field: 'taskReceivables',
          show: true
        },
        {
          label: '实收款',
          field: 'taskActualCollection',
          show: true
        },
        {
          label: '未收款',
          field: 'taskUncollected',
          show: true
        },
        {
          label: '回款率(%)',
          field: 'taskCollectionProportion',
          show: true
        },
      ];
    },
  },
};
</script>

<style lang="scss">

html,
body {
  height: 100%;
}

.level-padding {
  padding: 0 5px;
}

.advanced-search-linkman {
  .el-select-dropdown__item {
    height: 50px;
    padding: 5px 20px;
    p {
      margin: 0;
      line-height: 20px;
    }
  }
}

.report-advance-setting .el-dropdown-menu__item {
  width: 80px;
  text-align: center;
}

.report-list-container {
  height: 100%;
  overflow: auto;
  padding: 10px;

  .panel-title {
    font-size: 16px;
    line-height: 60px;
    padding: 0 25px;
    color: rgb(132, 138, 147);
    border-bottom: 1px solid rgb(242, 248, 247);
    font-weight: normal;
    display: flex;
    justify-content: space-between;
    .iconfont:hover {
      cursor: pointer;
    }
  }
}

.report-list-title-group-container{
  margin-bottom: 10px;
  background-color: #fff;
  border-radius: 3px;
  padding: 12px 10px;
  .title{
    font-weight: 600;
    font-size:16px ;
    margin-bottom: 5px;
  }
}

// search
.report-list-search-group-container {
  .advanced-search-function,
  .base-search {
    background: #fff;
    border-radius: 3px;
  }

  .base-search {
    font-size: 14px;
    display: flex;
    justify-content: space-between;
    padding: 12px 10px;

    .report-list-base-search-group {
      display: flex;

  

      .el-select{
        width:200px;
        margin-right:10px ;
        .el-input {
            width: 100%;
            input {
                height: 32px;
                line-height: 32px;
                width: 100%;
            }
        }
        .biz-team-select p{
            line-height: 26px;
        }
      }

      .el-input {
        width: 40%;
        margin-right:10px ;
        input {
          height: 32px;
          line-height: 32px;
          width: 100%;
        }
      }

      .base-button{
        height: 32px;
        width: 80px;
        margin: 0 5px;
      }

      .el-range-editor {
        margin-right:10px ;
        width:400px !important;
        input{
            width: 150px;
        }
      }

      a {
        line-height: 33px;
      }
    }

    .advanced-search-visible-btn {
      font-size: 14px;
      line-height: 32px;
      color: $color-primary;
      border-color: $color-primary;
      background: #fff;
      padding: 0 13px;
      white-space: nowrap;

      &:hover {
        cursor: pointer;
      }

      .iconfont {
        font-size: 12px;
        font-weight: bolder;
      }
    }
  }

  .advanced-search-form {
    overflow: auto;
    padding: 10px 0 63px 0;
    height: calc(100% - 51px);

    .form-item-container {
    }

    .two-columns {
      display: flex;
      flex-wrap: wrap;
      .el-form-item {
        width: 50%;
      }
    }

    .el-form-item {
      .el-form-item__content,
      .el-select,
      .base-dist-picker,
      .el-cascader,
      .el-date-editor {
        width: 290px;
      }
    }

    .advanced-search-btn-group {
      display: flex;
      justify-content: flex-end;
      width: 100%;
      position: absolute;
      bottom: 0px;
      background: #fff;
      padding: 15px 20px;

      .base-button {
        margin: 0 10px;
      }
    }
  }

  .advanced-search-function {
    margin-top: 10px;
    padding-bottom: 10px;

    h4 {
      border-bottom: 1px solid #f4f4f4;
      padding: 10px;
    }

    .el-row {
      padding: 5px 0;
    }
    .input-label {
      text-align: right;
      line-height: 32px;
      padding-right: 0;
    }
  }
}

// list
.report-list-component {
  padding-top: 10px;
  /*min-height: calc(100% - 100px);*/

  .report-table {
    padding: 10px;

    &:before {
      height: 0;
    }

    .report-table-header th {
      background: #f5f5f5;
      color: $text-color-primary;
      font-weight: normal;
    }

      .view-detail-btn {
        width: 100%;
        color: $color-primary;
      }

    .view-detail-btn {
      color: $color-primary;
    }

    .select-column .el-checkbox {
      position: relative;
      top: 3px;
    }
  }

  .table-footer {
    display: flex;
    justify-content: space-between;
    padding: 0px 10px 10px 10px;
    background: #fff;
    border-radius: 0 0 3px 3px;

    .list-info {
      font-size: 13px;
      line-height: 32px;
      margin: 0;
      color: #767e89;

      .iconfont {
        position: relative;
        top: 1px;
      }
    }

    .el-pagination__jump {
      margin-left: 0;
    }
  }
}

.report-panel-btn {
  float: right;
  cursor: pointer;
  font-size: 14px;
  margin-right: 5px;

  &:hover {
    color: $color-primary;
  }
}

// -------- report selected panel --------
.report-selected-count {
  color: $color-primary;
  padding: 0 3px;
  width: 15px;
  text-align: center;
  cursor: pointer;
  font-size: 13px;
}

.report-selected-panel {
  font-size: 14px;
  height: calc(100% - 51px);

  .report-selected-tip {
    padding-top: 80px;

    img {
      display: block;
      width: 240px;
      margin: 0 auto;
    }

    p {
      text-align: center;
      color: #9a9a9a;
      margin: 30px 0 0 0;
      line-height: 20px;
    }
  }

  .report-selected-list {
    height: 100%;
    padding: 10px;
    overflow-y: auto;

    .report-selected-row {
      display: flex;
      flex-flow: row nowrap;
      line-height: 36px;
      border-bottom: 1px solid #ebeef5;
      font-size: 13px;

      &:hover {
        background-color: #f5f7fa;

        .report-selected-delete {
          visibility: visible;
        }
      }
    }

    .report-selected-head {
      background-color: #f0f5f5;
      color: #333;
      font-size: 14px;
    }

    .report-selected-sn {
      padding-left: 10px;
      width: 150px;
      @include text-ellipsis;
    }

    .report-selected-name {
      padding-left: 10px;
      flex: 1;
      @include text-ellipsis;
    }

    .report-selected-delete {
      width: 36px;
    }

    .report-selected-row button.report-selected-delete {
      padding: 0;
      width: 36px;
      height: 36px;
      border: none;
      background-color: transparent;
      outline: none;
      color: #646b78;
      visibility: hidden;

      i {
        font-size: 14px;
      }

      &:hover {
        color: #e84040;
      }
    }
  }
}

// operation
.report-columns-dropdown-menu {
  max-height: 300px;
  overflow: auto;
  .el-dropdown-menu__item {
    padding: 0;
  }
  .el-checkbox {
    width: 100%;
    padding: 5px 15px;
    margin: 0;
  }
}

.operation-bar-container {
  background: #fff;
  border-radius: 3px 3px 0 0;
  display: flex;
  justify-content: flex-end;
  padding: 10px;

  .top-btn-group .base-button {
    margin-right: 5px;
  }

  .action-button-group {
    .base-button {
      margin-left: 5px;
    }
  }

  .el-dropdown-btn {
    padding: 0 15px;
    line-height: 32px;
    display: inline-block;
    background: $color-primary-light-9;
    color: $text-color-primary;
    outline: none;
    margin-left: 5px;
    .iconfont {
      margin-left: 5px;
      font-size: 12px;
    }

    &:hover {
      cursor: pointer;
      color: #fff;
      background: $color-primary;
    }
  }
}

// superscript
.report-name-superscript-td {
  padding: 0 !important;
  & > div {
    height: 43px;
    line-height: 43px !important;
    a {
      display: inline-block;
      height: 43px;
      line-height: 43px;
    }
  }
}
</style>
<style lang="scss" scoped>
    ::v-deep .el-table__fixed{
        margin: 10px;
    }

    ::v-deep .el-table__fixed-footer-wrapper{
      padding: 20px 0;
    }
</style>
